package com.dw.common.util;

import com.dw.common.bean.ResourceBean;
import com.dw.common.configuration.Configuration;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class ResourceScanner {
    public static Map<ResourceBean, String> scan(String path) {
        Map<ResourceBean, String> resources = new HashMap<>();
        File root = new File(path);
        if (root.exists()) {
            if (root.isDirectory()) {
                for (File file : Objects.requireNonNull(root.listFiles())) {
                    putResources(file, resources);
                }
            } else {
                putResources(root, resources);
            }
        }
        return resources;
    }

    public static Map<ResourceBean, String> scanOnlyFiles(String path) {
        Map<ResourceBean, String> resources = new HashMap<>();
        File root = new File(path);
        if (root.exists()) {
            scanOnlyFiles(root, resources);
        }
        return resources;
    }

    private static void scanOnlyFiles(File root, Map<ResourceBean, String> resources) {
        if (root.isDirectory()) {
            for (File file : Objects.requireNonNull(root.listFiles())) {
                if (file.isDirectory()) {
                    scanOnlyFiles(file, resources);
                } else {
                    putResources(file, resources);
                }
            }
        }
    }

    public static void putResources(File file, Map<ResourceBean, String> resources) {
        ResourceBean resource = new ResourceBean();
        resource.setName(file.getName());
        resource.setLength(file.length());
        resource.setOwner(Configuration.ORGANIZATION_ID);
        resources.put(resource, file.getAbsolutePath());
    }
}
